package com.kedou.sdk.ui.activity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.kedou.sdk.assist.AlipayPayOperation;
import com.kedou.sdk.assist.CallbackObservable;
import com.kedou.sdk.assist.Constant;
import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.handler.SimpleAsyncResponseHandler;
import com.kedou.sdk.params.CreateOrderResponseParams;
import com.kedou.sdk.params.PlatFormCoinResponseParams;
import com.kedou.sdk.params.ResponseParams;
import com.kedou.sdk.params.bean.Goods;
import com.kedou.sdk.params.bean.PayChannel;
import com.kedou.sdk.params.bean.PayChannelPlatCoin;
import com.kedou.sdk.params.bean.PlatCoinCurrency;
import com.kedou.sdk.params.bean.PlatCoinRate;
import com.kedou.sdk.params.bean.State;
import com.kedou.sdk.utils.ResUtils;
import com.squareup.picasso.Picasso;

import java.util.List;

public class PlatFormCoinActivity extends AppBaseActivity{


    private GridView moneyGridView;
    private BaseAdapter moneyAdapter;
    private GridView typeGridView;
    private BaseAdapter typeAdapter;
//    String[] mMoney;
    private int seletPosition = 0;
    private int typeSelecPosition = 0;
    private ImageView backImage;
    private TextView accountText,balanceText,biliText,confirmText;
    private EditText moneyEdit;
    private Goods mGoods;
    private List<PlatCoinCurrency> moneyList;
    private List<PayChannel> channelList;
    private PayChannelPlatCoin myInfo;
    private PlatCoinRate mRate;
    private int number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGoods = getIntent().getParcelableExtra("goods");
        setContentView(getLayoutIdentifier("hnssn_activity_platform_coin"));
//        mMoney = new String[]{"aaaaa", "bbbbbb", "ccccc", "dddd", "ffff"};
        moneyGridView = findViewById(getViewIdentifier("platform_coin_money_gird"));
        typeGridView = findViewById(getViewIdentifier("platform_coin_type_gird"));
        accountText = findViewById(getViewIdentifier("platform_coin_account"));
        balanceText = findViewById(getViewIdentifier("platform_coin_money"));
        biliText = findViewById(getViewIdentifier("platform_coin_bili"));
        confirmText = findViewById(getViewIdentifier("platform_coin_confirm"));
        moneyEdit = findViewById(getViewIdentifier("login_account_account"));
        moneyEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.e("PlatFormCoinActivity","onFocusChange"+hasFocus);
                if(hasFocus){
//                    seletPosition= -1;
//                    moneyAdapter.notifyDataSetChanged();
//                    confirmText.setText("确认支付 ￥");
//                    number = 0;
                }
            }
        });
        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString().toString();
                if(moneyEdit.isFocused()){
                    if(!TextUtils.isEmpty(temp)){
                        number = Integer.parseInt(temp);
                        confirmText.setText("确认支付 ￥"+number/mRate.getData());
                    }else{
                        if(seletPosition!=-1){
                            number = moneyList.get(seletPosition).getCurrency();
                            confirmText.setText("确认支付 ￥"+number/mRate.getData());
                        }
                    }
                }

            }
        });
        confirmText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGoods.setGoodsPrice(number/mRate.getData());
                String type = channelList.get(typeSelecPosition).getId();
                SimpleAsyncResponseHandler handler = requestCallbackHandler(CreateOrderResponseParams.class, type);
                mCreateOrderTaskId = HttpEngineApi.getInstance().createPlatCoinOrder(type,number+"", handler);

            }
        });
        backImage = findViewById(getViewIdentifier("platform_coin_close"));
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(getViewIdentifier("platform_coin_detail")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PlatFormCoinActivity.this,PlatFormCoinDetailActivity.class);
                intent.putExtra("info",myInfo);
                startActivity(intent);
            }
        });



//initData();
//        setData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        moneyEdit.setText("");
    }

    private int mGetPayChannelTaskId,mCreateOrderTaskId;
    private void initData(){
        SimpleAsyncResponseHandler handler = requestCallbackHandler(PlatFormCoinResponseParams.class);
        mGetPayChannelTaskId = HttpEngineApi.getInstance().platformCoin(mGoods, handler);
    }

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (flag == mCreateOrderTaskId) {

            executeCreateOrderResult(response);
        }else if (flag == mGetPayChannelTaskId){
            PlatFormCoinResponseParams responseParams = (PlatFormCoinResponseParams) response;
            if (State.SUCCESS == responseParams.getCode()) {
                moneyList = responseParams.getData().getCurrencyList();
                channelList = responseParams.getData().getPayList();
                myInfo = responseParams.getData().getCurrencyUser();
                mRate = responseParams.getData().getProportion();
                setData();
            }
        }

    }

    private void executeCreateOrderResult(ResponseParams response) {
        if (response instanceof CreateOrderResponseParams) {
            CreateOrderResponseParams responseParams = (CreateOrderResponseParams) response;
            HttpEngineApi.getInstance().getEngineConduits().saveCurrentOrder(responseParams.getData().getOrder_no());
            if(1==responseParams.getData().getPayment_success()){
                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_success"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, message, null);
                finish();
            }else {
                if (State.SUCCESS == responseParams.getCode()) {

                    switch (responseParams.getData().getOpen_with()) {
                        case 2:
                            weixinPay(responseParams.getData());
                            break;

                        case 3:
                            alipayPayV1(responseParams.getData());
                            break;
                        default:
                            startDefaultWebBrowser(responseParams.getData());
                            break;
                    }
                }

            }
        }


//        if (response instanceof CreateOrderResponseParams) {
//            CreateOrderResponseParams responseParams = (CreateOrderResponseParams) response;
//            if (State.SUCCESS == responseParams.getCode()) {
//                switch (payType) {
//                    case WEIXIN_PAY:
//                        weixinPay(responseParams.getData());
//                        break;
//
//                    case WEIXIN_APPLET_PAY:
//                        weixinAppletPay(responseParams.getData());
//                        break;
//
//                    case ALIPAY_PAY:
//                    case HAOGE_PAY:
//                        alipayPayV1(responseParams.getData());
//                        break;
//
//                    case UNION_PAY:
//                    case PAYPAL_PAY:
//                    case LEYUN_PAY:
//                    case UNDER_LINE_PAY:
//                        webH5Pay(responseParams.getData());
//                        break;
//                    case WECHAT_APP_PAY:
//                        weixinAppPay(responseParams.getData());
//                        break;
//                    case DEFAULT_WEB_BROWSER:
//                        startDefaultWebBrowser(responseParams.getData());
//                        break;
//
//
//
//                    default:
//                        DialogFactory.createConfirmDialog(this, getString(getStringIdentifier("hnssn_hint_payerror"))).show();
//                }
//            }
//        }
    }

    private void alipayPayV1(final CreateOrderResponseParams.CreateOrderResponseData response) {
        Log.d("alipay","alipayPayV1");
        if (response != null) {
            new AlipayPayOperation(this).execute(response.getPay_info());
        }
    }
    private void weixinAppletPay(CreateOrderResponseParams.CreateOrderResponseData response) {
        if (response != null) {
            Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_WECHAT_APPLET_PAY);
            intent.setPackage(getPackageName());
            intent.putExtra("wechat_applet_pay_info", response.getPay_info());
            startActivityForResult(intent, APPLET_REQUEST_CODE);
        }
    }
    private static final int START_DEFAULT_BROWSER_REQUEST_CODE = 0x0003;
    private static final int REQUEST_CODE = 0x0000;
    private static final int APPLET_REQUEST_CODE = 0x0001;
    private void startDefaultWebBrowser(final CreateOrderResponseParams.CreateOrderResponseData response) {
        String url = response != null ? response.getPay_info(): "";
        if (!TextUtils.isEmpty(url)) {
            try {
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), START_DEFAULT_BROWSER_REQUEST_CODE);
            } catch (ActivityNotFoundException exception) {
                final int resId = getStringIdentifier("hnssn_h5payhint_webclient_excepition");
                Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_SHORT).show();

                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
            }
        } else {
            CallbackObservable observable = CallbackObservable.getInstance();
            String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
        }
    }

    private void weixinPay(CreateOrderResponseParams.CreateOrderResponseData response) {
        if (response != null) {
            int type = 0;

            webH5Pay(response);
//            switch (type) {
//                case 2:
//                    HeepayPayOperation.pay(this, response.getPay_info(), response.getOrder_no());
//                    break;
//                default:
//                    webH5Pay(response);
//            }
        }
    }
    private void weixinAppPay(CreateOrderResponseParams.CreateOrderResponseData response) {
        if (response != null) {
//            WeChatOperation.getInstance().startWeChatApplet(PlatFormCoinActivity.this,response.getPay_info());
        }
    }
    private void webH5Pay(final CreateOrderResponseParams.CreateOrderResponseData response) {
        Intent intent = new Intent(this, WXH5PayActivity.class);
        intent.setPackage(getPackageName());
        intent.putExtra("weixinPay", response);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("CoinActivity",requestCode+"..requestCode"+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Toast.makeText(getApplicationContext(),"充值成功",Toast.LENGTH_SHORT).show();
            initData();
        }
    }

    private void setData(){
        accountText.setText("充值账号："+myInfo.getUserName());
        balanceText.setText(myInfo.getCurrency());
        biliText.setText("（"+mRate.getName()+"）");
        number = moneyList.get(seletPosition).getCurrency();
        confirmText.setText("确认支付 ￥"+moneyList.get(seletPosition).getCurrency()/mRate.getData());
        initAdapter();
    }


    private void initAdapter(){
        if(moneyAdapter==null) {
            moneyAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return moneyList == null ? 0 : moneyList.size();
                }

                @Override
                public Object getItem(int position) {
                    return moneyList.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    MoneyViewHolder viewHolder;
                    if (convertView == null) {
                        viewHolder = new MoneyViewHolder();
                        final Context context = parent.getContext();
                        LayoutInflater inflater = LayoutInflater.from(context);
                        final int layoutResId = ResUtils.getLayoutIdentifier(context, "hnssn_item_platform_money");
                        final int titleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_title");
                        final int subtitleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_subtitle");
                        final int bgResId = ResUtils.getViewIdentifier(context, "item_platformcoin_bg");
                        convertView = inflater.inflate(layoutResId, parent, false);
                        viewHolder.title = convertView.findViewById(titleResId);
                        viewHolder.subTitle = convertView.findViewById(subtitleResId);
                        viewHolder.backView = convertView.findViewById(bgResId);
                        convertView.setTag(viewHolder);
                    } else {
                        viewHolder = (MoneyViewHolder) convertView.getTag();
                    }
                    PlatCoinCurrency money = moneyList.get(position);
                    viewHolder.title.setText(money.getCurrency() + "个");
                    if (money.getGive() == 0) {
                        viewHolder.subTitle.setVisibility(View.GONE);
                    } else {
                        viewHolder.subTitle.setVisibility(View.VISIBLE);
                        viewHolder.subTitle.setText(money.getGiveText());
                    }
                    if (position == seletPosition) {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hnssn_bg_platformcoin_money_select"));
                        viewHolder.title.setTextColor(Color.parseColor("#1D97FD"));
                    } else {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hn669_platformcoin_edit_bg"));
                        viewHolder.title.setTextColor(Color.parseColor("#333333"));
                    }
                    return convertView;
                }
            };
            moneyGridView.setAdapter(moneyAdapter);
            moneyGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    seletPosition = position;
                    moneyAdapter.notifyDataSetChanged();
                    moneyEdit.setText("");
                    number = moneyList.get(seletPosition).getCurrency();
                    confirmText.setText("确认支付 ￥" + number / mRate.getData());
                }
            });
        }else{
            moneyAdapter.notifyDataSetChanged();
        }
        if(typeAdapter==null) {
            typeAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return channelList == null ? 0 : channelList.size();
                }

                @Override
                public Object getItem(int position) {
                    return channelList.get(position);
                }

                @Override
                public long getItemId(int position) {
                    return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    TypeViewHolder viewHolder;
                    if (convertView == null) {
                        viewHolder = new TypeViewHolder();
                        final Context context = parent.getContext();
                        LayoutInflater inflater = LayoutInflater.from(context);
                        final int layoutResId = ResUtils.getLayoutIdentifier(context, "hnssn_item_platform_type");
                        final int titleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_title");
                        final int subtitleResId = ResUtils.getViewIdentifier(context, "item_platformcoin_icon");
                        final int bgResId = ResUtils.getViewIdentifier(context, "item_platformcoin_bg");
                        convertView = inflater.inflate(layoutResId, parent, false);
                        viewHolder.title = convertView.findViewById(titleResId);
                        viewHolder.icon = convertView.findViewById(subtitleResId);
                        viewHolder.backView = convertView.findViewById(bgResId);
                        convertView.setTag(viewHolder);
                    } else {
                        viewHolder = (TypeViewHolder) convertView.getTag();
                    }
                    PayChannel channel = channelList.get(position);
                    viewHolder.title.setText(channel.getName());
                    Picasso.with(PlatFormCoinActivity.this).load(channel.getIconUrl()).into(viewHolder.icon);
                    if (position == typeSelecPosition) {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hnssn_bg_platformcoint_type_select"));
//                    viewHolder.title.setTextColor(Color.parseColor("#1D97FD"));
                    } else {
                        viewHolder.backView.setBackgroundResource(ResUtils.getDrawableIdentifier(PlatFormCoinActivity.this, "hn669_platformcoin_edit_bg"));
//                    viewHolder.title.setTextColor(Color.parseColor("#333333"));
                    }
                    return convertView;
                }
            };
            typeGridView.setAdapter(typeAdapter);
            typeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    typeSelecPosition = position;
                    typeAdapter.notifyDataSetChanged();
                }
            });
        }else {
            typeAdapter.notifyDataSetChanged();
        }

    }

    public static class MoneyViewHolder {
        public TextView title;
        public TextView subTitle;
        private LinearLayout backView;
    }
    public static class TypeViewHolder {
        public TextView title;
        public ImageView icon;
        private LinearLayout backView;
    }
}
